﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using Token.Piker.Core.Security;
using Token.Piker.Core.Photo;
using Token.Piker.Core.Album;
using Token.Util;
using System.Collections;
using Token.Piker.Common;

namespace Token.Piker.Web.AJAX
{
    /// <summary>
    /// Upload 的摘要说明
    /// </summary>
    public class Upload : BaseAjaxHandler
    {
        ThumbnailImage thumb = new ThumbnailImage();
        //Token.Piker.Core.Album.Album ablum_proxy = new Token.Piker.Core.Album.Album();
        public class responseTemplate
        {
            public string uid;
            public string url;
        }

        public class photo_dict
        {
            public Token.Piker.Model.Photo photo;
            public DateTime time;
        }

        protected override void Mapping()
        {
            OprationMap["multi"] = "UploadPhoto";
            OprationMap["single"] = "UploadPhoto";
            OprationMap["IssueMulti"] = "IssueMulti";
            OprationMap["IssueSingle"] = "IssueSingle";
        }


        /// <summary>
        /// 图片上传的方法
        /// </summary>
        public void UploadPhoto()
        {
            //处理POST
            if (Context.Request.HttpMethod == "POST")
            {
                string id = Context.Session[GlobalConstants.PIKER_USER_ID].ToString();
                HttpFileCollection files = Context.Request.Files;
                IList<responseTemplate> list = new List<responseTemplate>();
                for (int i = 0; i < files.Count; i++)
                {
                    HttpPostedFile file = files[i];

                    Stream fs = file.InputStream;
                    System.Drawing.Image img = System.Drawing.Image.FromStream(fs);

                    //新建photo对象
                    Token.Piker.Model.Photo photo = new Token.Piker.Model.Photo();

                    var size = ComputeSize(img);
                    Stream[] photo_stream = new Stream[4];
                    FileStream fs_src = null;
                    string[] url = new string[5];

                    try
                    {
                        string folder_path = FileHelper.GetUploadPathToday();
                        string hash = DateTime.Now.GetHashCode().ToString();
                        string path_src = folder_path + hash + "_src_" + Path.GetExtension(file.FileName);       //保存原图  
                        //fs_src = File.Create(Context.Request.MapPath(path_src));

                        //byte[] fb = new byte[fs.Length];
                        file.SaveAs(Context.Request.MapPath(path_src));

                        url[0] = path_src;
                        for (int j = 0; j < 4; j++)   //挨个生产缩略图
                        {
                            string Compress_path = folder_path + hash + "_cop_" + j + Path.GetExtension(file.FileName);
                            photo_stream[j] = File.Create(Context.Request.MapPath(Compress_path), 1024);
                            //生成缩略图
                            thumb.ToThumbnailImage(fs, photo_stream[j], size[1, j], size[0, j]);

                            url[j + 1] = Compress_path;

                        }
                        //fs.Dispose();

                    }
                    catch (System.Exception ex)
                    {
                        LogHelper.Log(ex.Message);
                        IsSuccess = false;
                        Message = ex.Message;
                        return;
                    }
                    finally   //释放资源
                    {
                        if (fs != null)
                        {
                            fs.Close();
                        }
                        if (fs_src != null)
                        {
                            fs_src.Close();
                        }
                        for (int m = 0; m < photo_stream.Length; m++)
                        {
                            if (photo_stream[m] != null)
                                photo_stream[m].Close();
                        }
                    }

                    //保存到photo
                    string guid = System.Guid.NewGuid().ToString();
                    ExifGetter exif_info = new ExifGetter(System.Drawing.Image.FromFile(Context.Request.MapPath(url[0])));
                    photo.SourceUrl = url[0];
                    photo.CompressUrl_1 = url[1];
                    photo.CompressUrl_2 = url[2];
                    photo.CompressUrl_3 = url[3];
                    photo.CompressUrl_4 = url[4];
                    photo.UserID = Convert.ToInt32(id);
                    photo.ExifVersionExif = "";  //版本 TODO
                    photo.ExposureProgram = ""; //曝光程序 TODO
                    photo.ExposureTime = exif_info.ExposureTime; //曝光时间
                    photo.FNumber = exif_info.ApertureValue;  //光圈
                    photo.Lightsource = exif_info.FocalLength;  //焦距
                    photo.ISO = exif_info.Iso; //ISO
                    photo.Make = exif_info.Manufacturers;
                    photo.Model = exif_info.Model;

                    photo_dict dict = new photo_dict();
                    dict.photo = photo;
                    dict.time = System.DateTime.Now;

                    UpdateMap(guid, dict);

                    responseTemplate temp = new responseTemplate();
                    temp.uid = guid;
                    temp.url = url[1];   //返回这个尺寸
                    list.Add(temp);

                    //释放
                    img.Dispose();

                }


                if (list.Count > 0)
                {
                    IsSuccess = true;
                    ResponseTemplate(list);
                }
                else
                {
                    IsSuccess = false;
                }


            }


        }

        /// <summary>
        /// 发布单张
        /// </summary>
        public void IssueSingle()
        {
            //处理Post请求
            if (Context.Request.HttpMethod != "POST")
            {
                return;
            }

            try
            {
                string id = Context.Session[GlobalConstants.PIKER_USER_ID].ToString();

                issueSinglePhoto(id);

                IsSuccess = true;
                responseTemplate model = new responseTemplate();
                model.uid = id;
                model.url = "";  //TODO 跳转到相册界面？  返回要跳转的页面 还是提示继续添加

                ResponseTemplate(model);
            }
            catch
            {
                IsSuccess = false;
            }
        }

        /// <summary>
        /// 发布单张图片
        /// </summary>
        protected void issueSinglePhoto(string userid)
        {
            //获取传来的参数
            string type_cont = (Context.Request.Form["type_cont"] == null) ? "" : Context.Request.Form["type_cont"];  //与ajax的parm属性对应，自己调试下
            string type_style = (Context.Request.Form["type_style"] == null) ? "" : Context.Request.Form["type_style"];
            string position = (Context.Request.Form["position"] == null) ? "" : Context.Request.Form["position"];
            string descrip = (Context.Request.Form["descrip"] == null) ? "" : Context.Request.Form["descrip"];
            string size_s = (Context.Request.Form["size"] == null) ? "0" : Context.Request.Form["size"];

            string PID = (Context.Request.Form["PID"] == null) ? "" : Context.Request.Form["PID"];  //图片ID

            var result = UploadMap.Find(delegate(DictionaryEntry e)
            {
                return (e.Key.ToString() == PID) ? true : false;
            });


            foreach (var p in result)
            {
                var dict = (photo_dict)p.Value;
                dict.photo.LikeCount = 0;
                dict.photo.UploadTime = DateTime.Now;

                //添加图片地址描述信息等
                dict.photo.Position = position;
                dict.photo.Descrip = descrip;
                dict.photo.UserID = Convert.ToInt32(userid);

                //添加图片到数据库
                int pid = PhotoProxy.AddPhoto(dict.photo);


                //添加图片Tag信息
                if (type_cont != "")
                    PhotoProxy.AddPhotoTag(Convert.ToString(pid), type_cont);
                if (type_style != "")
                    PhotoProxy.AddPhotoTag(Convert.ToString(pid), type_style);
            }

            UploadMap.Remove(delegate(DictionaryEntry e)
            {
                return (e.Key.ToString() == PID) ? true : false;

            });
        }


        public void IssueMulti()
        {
            //处理Post请求
            if (Context.Request.HttpMethod != "POST")
            {
                return;
            }

            try
            {
                string id = Context.Session[GlobalConstants.PIKER_USER_ID].ToString();
                string type_cont = (Context.Request.Form["type_cont"] == null) ? "" : Context.Request.Form["type_cont"];  //与ajax的parm属性对应，自己调试下
                string type_style = (Context.Request.Form["type_style"] == null) ? "" : Context.Request.Form["type_style"];
                string position = (Context.Request.Form["position"] == null) ? "" : Context.Request.Form["position"];
                string descrip = (Context.Request.Form["descrip"] == null) ? "" : Context.Request.Form["descrip"];
                string size_s = (Context.Request.Form["size"] == null) ? "0" : Context.Request.Form["size"];
                string isNewAlbum = (Context.Request.Form["isNewAlbum"] == null) ? "" : Context.Request.Form["isNewAlbum"];
                string AlbumName = (Context.Request.Form["AlbumName"] == null) ? "" : Context.Request.Form["AlbumName"];
                string AlbumID = "";

                //是否新建相册
                if (isNewAlbum == "1")
                {
                    Token.Piker.Model.Album ablum = new Token.Piker.Model.Album();
                    ablum.AlbumName = AlbumName;
                    ablum.CreateTime = DateTime.Now;
                    ablum.Descrip = descrip;
                    //ablum.Position = position;
                    ablum.UserID = Convert.ToInt32(id);
                    int new_AID = AlbumProxy.AddAlbum(ablum);
                    AlbumID = Convert.ToString(new_AID);
                }
                else
                {
                    AlbumID = AlbumName;
                }

                issueMutliPhoto(AlbumID, id);

                //for (int i = 0; i < Convert.ToInt32(size_s); i++)
                //{
                //    //添加相册Tag信息
                //    //if (type_cont != "")
                //    //    AlbumProxy.AddAlbumTag(AlbumID, type_cont);
                //    //if (type_style != "")
                //    //    AlbumProxy.AddAlbumTag(AlbumID, type_style);


                //    //发布图片




                //}


                IsSuccess = true;
                responseTemplate model = new responseTemplate();
                model.uid = id;
                model.url = "";  //跳转到相册界面？  返回要跳转的页面 还是提示继续添加

                ResponseTemplate(model);
            }
            catch
            {
                IsSuccess = false;
            }
        }

        /// <summary>
        /// 将UploadMap发布Photo
        /// </summary>
        /// <param name="aid">相册ID</param>
        protected void issueMutliPhoto(string aid, string userid)
        {
            //获取传来的参数
            string type_cont = (Context.Request.Form["type_cont"] == null) ? "" : Context.Request.Form["type_cont"];  //与ajax的parm属性对应，自己调试下
            string type_style = (Context.Request.Form["type_style"] == null) ? "" : Context.Request.Form["type_style"];
            string position = (Context.Request.Form["position"] == null) ? "" : Context.Request.Form["position"];
            string size_s = (Context.Request.Form["size"] == null) ? "0" : Context.Request.Form["size"];
            List<string[]> list_pid = new List<string[]>();

            for (int i = 0; i < Convert.ToInt32(size_s); i++)
            {
                string[] item = new string[2];
                item[0] = Context.Request.Form["imgInfo[" + i + "][PID]"];
                item[1] = Context.Request.Form["imgInfo[" + i + "][Pdiscrip]"];
                list_pid.Add(item);
            }
            var result = UploadMap.Find(delegate(DictionaryEntry e)
            {
                return list_pid.Exists(delegate(string[] k)
                {
                    return (e.Key.ToString() == k[0]) ? true : false;
                });

            });

            foreach (var p in result)
            {
                var dict = (photo_dict)p.Value;
                dict.photo.LikeCount = 0;
                dict.photo.UploadTime = DateTime.Now;

                //添加图片地址描述信息等
                dict.photo.Position = position;
                dict.photo.UserID = Convert.ToInt32(userid);
                string[] temp = list_pid.Find(delegate(string[] k)
                {
                    return (p.Key.ToString() == k[0]) ? true : false;
                });
                dict.photo.Descrip = temp[1];

                //添加图片到数据库
                dict.photo.Album = Convert.ToInt32(aid);

                //更新封面
                PhotoProxy.UpdateAlbumCover(dict.photo);

                int pid = PhotoProxy.AddPhoto(dict.photo);

                //相册关联
                //AlbumProxy.AddPhotoAlbum(aid, Convert.ToString(pid));



                //添加图片Tag信息
                if (type_cont != "")
                    PhotoProxy.AddPhotoTag(Convert.ToString(pid), type_cont);

                if (type_style != "")
                    PhotoProxy.AddPhotoTag(Convert.ToString(pid), type_style);
            }

            UploadMap.Remove(delegate(DictionaryEntry e)
            {
                return list_pid.Exists(delegate(string[] k)
                {
                    return (e.Key.ToString() == k[0]) ? true : false;
                });

            });
        }

        /// <summary>
        /// 更新PhotoMap，每上传一次图片GC一次
        /// </summary>
        /// <param name="id"></param>
        /// <param name="p"></param>
        protected void UpdateMap(string id, photo_dict p)
        {
            //添加
            DictionaryEntry dict_entry = new DictionaryEntry(id, p);
            UploadMap.Add(dict_entry);

            //检查30分钟未操作的元素，Remove掉
            UploadMap.Remove(delegate(DictionaryEntry e)
            {
                var dict = e.Value as photo_dict;
                TimeSpan ts = DateTime.Now.Subtract(dict.time);
                if (ts.Minutes >= 30)
                {
                    return true;
                }
                return false;
            });

        }


        /// <summary>
        /// 计算最适合的压缩大小 第一行为height 第二行为width
        /// </summary>
        /// <param name="img">img</param>
        /// <returns></returns>
        protected int[,] ComputeSize(System.Drawing.Image img)
        {
            int[,] ProSize = new int[2, 4];
            int[,] StandSize = GlobalConstants.Photo_Size;
            decimal width = img.Width,
                height = img.Height;
            //图片实际比例
            decimal rate = height / width;
            for (int i = 0; i < 4; i++)
            {
                decimal stand_rate = (decimal)StandSize[0, i] / (decimal)StandSize[1, i];
                if (stand_rate > rate)   //原图比标准比例要宽
                {
                    ProSize[0, i] = StandSize[0, i];
                    ProSize[1, i] = Convert.ToInt32(StandSize[0, i] / rate);
                }
                else
                {
                    ProSize[1, i] = StandSize[1, i];
                    ProSize[0, i] = Convert.ToInt32(StandSize[1, i] * rate);
                }
            }

            return ProSize;
        }

    }
}